package com.shujia.scala

import java.io.{BufferedReader, FileReader, FileWriter, PrintWriter}
import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}
import scala.io.{BufferedSource, Source}

object Demo7FileIOAndJDBC {
  def main(args: Array[String]): Unit = {
    // Java中的文件读写
    val br = new BufferedReader(new FileReader("data/students.txt"))
    var line = br.readLine()
    while (line != null) {
      println(line)
      line = br.readLine()
    }
    br.close()
    println("#" * 100)
    // Scala中的文件读写
    val source: BufferedSource = Source.fromFile("data/students.txt")
    val sIt: Iterator[String] = source.getLines()
    for (line <- sIt) {
      println(line)
    }
    println("#" * 100)
    // 简写
    // 链式调用
    Source.fromFile("data/students.txt")
      .getLines()
      .foreach(println)


    // 写文件
    // PrintWriter FileWriter
    val writer = new PrintWriter("data/output1.txt")
    writer.println("helloWorld") // 会加上换行符
    writer.write("helloWorld") // 不会换行
    writer.close()

    val writer1 = new FileWriter("data/output2.txt")
    writer1.write("ok\n")
    writer1.write("ok\n")
    writer1.write("ok\n")
    writer1.close()


    // JDBC
    // scala中没有正对JDBC做特定的优化
    // 实际上用的是Java那一套流程
    Class.forName("com.mysql.jdbc.Driver")
    val conn: Connection = DriverManager.getConnection("jdbc:mysql://rm-bp1h7v927zia3t8iwho.mysql.rds.aliyuncs.com:3306/students", "masu001", "123456")
    val stat: PreparedStatement = conn.prepareStatement("select * from students where age = ?")
    stat.setInt(1, 23)
    val set: ResultSet = stat.executeQuery()
    while (set.next()) {
      val name: String = set.getString("name")
      val age: Int = set.getInt("age")
      val clazz: String = set.getString("clazz")
      println(s"${name},${age},${clazz}")

    }

  }

}
